#Alexander F. Gazmararian
#afg2@princeton.edu

#load packages
library(tidyverse)

#load functions
source("code/fun/book_theme.r")
source("code/fun/savefig.r")

#load 2022 county fair data
fair <- readRDS("data/FairGazmararian_2022.rds")

#load national public data
g <- readRDS("data/NatQual_August22.rds")

# Merge National and Fair
#select relevant fair questions
fair_sub <- subset(fair, select = c(GreenJobs_goodpay:GreenJobs_support,GreenJobs_goodpay_i:GreenJobs_support_of,weights))
fair_sub$sample <- "County Fair"

#select relevant national questions
nat_sub <- subset(g, select = c(GreenJobs_goodpay:GreenJobs_support,receiveNewsRenew_sc:GreenJobs_support_of))
nat_sub$weights <- 1
nat_sub$sample <- "National"

#harmonize variables for merging
g <- bind_rows(fair_sub, nat_sub)

# Create Figure 4.3 ------------------------------------------
greenjobplot <-
  g %>%
  select(ends_with("i") | ends_with("sample")) %>%
  pivot_longer(cols = c(GreenJobs_goodpay_i:GreenJobs_support_i)) %>%
  separate(col = name, into = c("variable", "outcome", "tag"), sep = "_") %>%
  filter(tag == "i") %>%
  group_by(outcome, sample) %>%
  summarise(
    mean = mean(value),
    lb = mean + qnorm(0.025) * sd(value) / sqrt(n()),
    ub = mean + qnorm(0.975) * sd(value / sqrt(n())),
    lb90 = mean + qnorm(0.05) * sd(value) / sqrt(n()),
    ub90 = mean + qnorm(0.95) * sd(value / sqrt(n()))
  ) %>%
  dplyr::mutate(
    outcome = dplyr::recode(
      factor(outcome),
      "beautiful" = "Renewable energy would be beautiful",
      "notradeoff" = "Renewable energy would NOT take up productive land",
      "nothreat" = "Renewable energy would NOT threaten fossil fuel jobs",
      "support" = "Support renewable energy investment",
      "goodpay" = "Renewable energy jobs would pay well",
      "climate" = "Renewable energy important to fight climate change"
    )
  ) %>%
  ggplot(aes(x = outcome, y = mean, color = sample, shape = sample, label = scales::percent(mean, accuracy = 1))) +
  geom_errorbar(aes(ymin = lb, ymax = ub), width = 0, position = position_dodge(.4)) +
  geom_errorbar(aes( ymin = lb90, ymax = ub90), width = 0, size = 1.75, position = position_dodge(.4)) +
  geom_point(size = 4, position = position_dodge(.4)) +
  geom_text(vjust = -1.5, size = 3, position = position_dodge(.4), aes(group = sample), color = "black") +
  coord_flip() +
  scale_y_continuous(labels = scales::percent_format(), limits = c(.24, .87), breaks = seq(.25, .85, .2)) +
  scale_x_discrete(labels = scales::label_wrap(20)) +
  labs(y = "Percent agree", x = "", caption = "Notes: Thin and thick bars denote 95 and 90 percent confidence intervals",
       color = "", shape = "") +
  scale_color_grey(start = 0, end = .6) +
  book_theme +
  theme(
    legend.position = "bottom",
    panel.grid.major.y  = element_line(color = "lightgrey", size = .25)
  )

greenjobplot

savefig(greenjobplot, "4.3_figure_greenbeliefs_fairnat", height = 3.5, filepath = "figures/")
